<template>
  <modal :visible="visible" title="新增" okText="保存" :width="1200" @cancelHandler="onClose" @okHandler="handleSubmit">
    <template slot="content">
      <a-spin :spinning="loading" :delay="200" tip="提交中...">
        <a-form :form="form">
          <a-form-item label="商品名称" v-bind="formItemLayout">
            <a-input
              v-decorator="[
                'title',
                { rules: [{ required: true, message: '商品名称不能为空' }, { max: 50, message: '字数不能超过50字' }], initialValue: initRecord.goodsName }
              ]"
            />
          </a-form-item>
          <a-form-item label="商品类别" v-bind="formItemLayout">
            <a-select
              :showArrow="true"
              v-decorator="[`categoryId`, { rules: [{ required: true, message: '商品类别不能为空' }], initialValue: initRecord.categoryId }]"
              placeholder="请选择商品类别"
              @change="categoryChange"
            >

              <a-select-option v-for="value in goodsCategorys" :key="value.id" :value="value.id">
                {{ value.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="二级分类" v-bind="formItemLayout">
            <a-select
              :showArrow="true"
              v-decorator="[`dictType`, { rules: [], initialValue: initRecord.dictType }]"
              placeholder="请选择二级分类"
              defaultActiveFirstOption
              allowClear
            >
              <a-select-option v-for="value in typeList" :key="value.dictCode" :value="value.dictValue">
                {{ value.dictLabel }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            v-bind="formItemLayout"
            v-for="(item, index) in renderImageData"
            :key="index + 'image'"
            :label="item.inputTitle"
            :extra="item.extra"
          >
            <a-upload
              :multiple="false"
              :accept="item.accept"
              :fileList="item.fileList"
              list-type="picture-card"
              :beforeUpload="beforeImageUpload"
              @change="handleImageChange(item.dataIndex, index, $event)"
              v-decorator="[
                `${item.dataIndex}`,
                {
                  rules: [
                    { required: (item.fileList.length > 0 && addOrEdit == 1) ? false : item.required, message: `${item.inputTitle}不能为空` },
                    {
                      validator: (rule, val, callback) =>
                        handleImageValidate(rule, val, callback, item.inputTitle, (item.fileList.length > 0 && addOrEdit == 1) ? false : item.required)
                    }
                  ],
                  validateTrigger: ['change'],
                  initialValue: initRecord.image
                }
              ]"
            >
              <a-button icon="upload">上传</a-button>
            </a-upload>
          </a-form-item>
          <a-form-item label="商品规格" v-bind="formItemLayout">
            <a-select
              :showArrow="true"
              v-decorator="['stat', { rules: [{ required: true, message: '请选择' }], initialValue: initRecord.specType }]"
              placeholder="请选择"
              :options="[
                  { key: 1, value: 1, title: '单规格' },
                  { key: 2, value: 2, title: '多规格' }
                ]"
            >
            </a-select>
          </a-form-item>
          <a-form-item label="商品编码" v-bind="formItemLayout" v-show="form.getFieldValue('stat') == 1">
            <a-input
              v-decorator="[
                'code',
                { rules: [{ required: true, message: '商品编码不能为空' }, { max: 50, message: '字数不能超过50字' }], initialValue: initRecord.goodsNo }
              ]"
            />
          </a-form-item>
          <a-form-item label="商品价格" v-bind="formItemLayout" v-show="form.getFieldValue('stat') == 1">
            <a-input-number
              style="width: 100%"
              :min="0"
              v-decorator="['price', { rules: [{ required: true, message: '商品价格不能为空' }], initialValue: initRecord.goodsPrice }]"
            />
          </a-form-item>
          <a-form-item label="商品划线价" v-bind="formItemLayout" v-show="form.getFieldValue('stat') == 1">
            <a-input-number
              style="width: 100%"
              :min="0"
              v-decorator="['linePrice', { rules: [{ required: true, message: '商品划线价不能为空' }], initialValue: initRecord.linePrice }]"
            />
          </a-form-item>
          <a-form-item label="当前库存数量" v-bind="formItemLayout" v-show="form.getFieldValue('stat') == 1">
            <a-input-number
              style="width: 100%"
              :min="0"
              :precision="0"
              v-decorator="['currentCount', { rules: [{ required: true, message: '当前库存数量不能为空' }], initialValue: initRecord.stockNum }]"
            />
          </a-form-item>
          <a-form-item label="商品重量" v-bind="formItemLayout" v-show="form.getFieldValue('stat') == 1">
            <a-input-number
              style="width: 100%"
              :min="0"
              :precision="0"
              v-decorator="['currentWeight', { rules: [{ required: true, message: '当前商品重量不能为空' }], initialValue: initRecord.goodsWeight }]"
            />
          </a-form-item>
          <a-form-item label="库存计算方式" v-bind="formItemLayout" v-show="form.getFieldValue('stat') == 1">
            <a-select
              :showArrow="true"
              v-decorator="['stats', { rules: [{ required: true, message: '请选择' }], initialValue: initRecord.deductStockType }]"
              placeholder="请选择"
              :options="[
                  { key: 1, value: 1, title: '下单减库存' },
                  { key: 2, value: 2, title: '付款减库存' }
                ]"
            >
            </a-select>
          </a-form-item>
          <a-form-item label="规格明细" v-bind="formItemLayout" v-show="form.getFieldValue('stat') == 2">
            <div style="border: 1px solid #E8E8E8; box-sizing: border-box; padding: 10px;">
              <div v-show="specList.length > 0">
                <div v-for="(specItem, specIndex) in specList" :key="specItem.id">
                  <div style="display: flex; flex-direction: row; align-items: center;">
                    <label>{{ specItem.specName }}</label>
                    <icon-font type="iconshanchu" style="margin-left: 10px; font-size: 15px"
                               @click="deleteSpecificationBtnClick(specIndex)"/>
                  </div>
                  <div style="display: flex; flex-direction: row; align-items: center;">
                    <div
                      style="display: flex; flex-direction: row; align-items: center; height: 32px; padding: 0 10px; margin-right: 10px; border: 1px solid #e8e8e8; box-sizing: border-box"
                      v-for="(specValueItem, specValueIndex) in specItem.values" :key="specValueItem.id">
                      <label>{{ specValueItem.specValue }}</label>
                      <icon-font type="iconshanchu" style="margin-left: 10px; font-size: 15px"
                                 @click="deleteSpecificationValueBtnClick(specIndex, specValueIndex)"/>
                    </div>
                    <div>
                      <a-input style="width: 150px;" v-model="specItem.specValueInput"></a-input>
                      <a-button type="primary" @click="saveSpecificationValueBtnClick(specIndex)">保存</a-button>
                    </div>
                  </div>
                </div>
              </div>
              <div v-show="!isShowAddSpecificationBtn">
                <a-form-item label="" v-bind="formItemLayout">
                  <div style="display: flex; flex-direction: row; align-items: center;">
                    <label>规格名</label>
                    <a-input style="width: 200px; margin-left: 10px"
                             v-decorator="['specificationNameInput',{ rules: [{ required: true, message: '规格名不能为空' }, { max: 50, message: '字数不能超过50字' }] }]"></a-input>
                  </div>
                </a-form-item>
                <a-form-item label="" v-bind="formItemLayout">
                  <div style="display: flex; flex-direction: row; align-items: center;">
                    <label>规格值</label>
                    <a-input style="width: 200px; margin-left: 10px"
                             v-decorator="['specificationValueInput',{ rules: [{ required: true, message: '规格值不能为空' }, { max: 50, message: '字数不能超过50字' }] }]"></a-input>
                  </div>
                </a-form-item>
                <div style="display: flex; flex-direction: row; align-items: center;">
                  <a-button type="primary" @click="saveSpecificationBtnClick">保存</a-button>
                  <a-button style="margin-left: 10px" @click="cancelSpecificationBtnClick">取消</a-button>
                </div>
              </div>
              <a-button type="primary" v-show="isShowAddSpecificationBtn" @click="addSpecificationBtnClick">添加规格
              </a-button>
              <div v-show="specSKUItems.length > 0">
                <a-table rowKey="id" :dataSource="specSKUItems" :columns="specSKUColumns" :pagination="false" :scroll="{x: true}">
                  <template slot="goodsNoScoped" slot-scope="text, record">
                    <a-input style="width: 100px;" v-model="record.goodsNo"></a-input>
                  </template>
                  <template slot="goodsPriceScoped" slot-scope="text, record">
                    <a-input-number :min="0" style="width: 80px;" v-model="record.goodsPrice"></a-input-number>
                  </template>
                  <template slot="linePriceScoped" slot-scope="text, record">
                    <a-input-number :min="0" style="width: 80px;" v-model="record.linePrice"></a-input-number>
                  </template>
                  <template slot="stockNumScoped" slot-scope="text, record">
                    <a-input-number :min="0" :precision="0" style="width: 80px;" v-model="record.stockNum"></a-input-number>
                  </template>
                  <template slot="goodsWeightScoped" slot-scope="text, record">
                    <a-input-number :min="0" :precision="0" style="width: 80px;" v-model="record.goodsWeight"></a-input-number>
                  </template>
                  <template slot="specImageScoped" slot-scope="text, record">
                    <img style="width: 50px; margin: 5px 0" :src="record.specImage" />
                  </template>
                  <template slot="uploadImageScoped" slot-scope="text, record">
                    <a-upload
                      :showUploadList="false"
                      :beforeUpload="beforeCoverImageUpload"
                      @change="handleCoverImageChange(record, $event)"
                    >
                      <a-button type="primary" style="padding: 0 3px">选择封面</a-button>
                    </a-upload>
                  </template>
                </a-table>
              </div>
            </div>
          </a-form-item>
          <a-form-item label="内容" v-bind="formItemLayout">
            <rich-editor :html="content" :id="'noticeAdd'" @editorChange="handleEditorChange" :height="300"/>
          </a-form-item>
          <a-form-item label="简介" v-bind="formItemLayout">
            <rich-editor :html="intro" :id="'noticeAd'" @editorChange="introChange" :height="100"/>
          </a-form-item>
          <a-form-item label="初始销量" v-bind="formItemLayout">
            <a-input-number
              style="width: 100%"
              :min="0"
              :precision="0"
              v-decorator="['defalutSales', { rules: [{ required: true, message: '初始销量不能为空' }], initialValue: initRecord.salesInitial }]"
            />
          </a-form-item>
          <a-form-item label="实际销量" v-bind="formItemLayout">
            <a-input-number
              style="width: 100%"
              :min="0"
              :precision="0"
              v-decorator="['sales', { rules: [{ required: true, message: '实际销量不能为空' }], initialValue: initRecord.salesActual }]"
            />
          </a-form-item>
          <a-form-item label="运费模版" v-bind="formItemLayout">
            <a-select
              :showArrow="true"
              v-decorator="[`deliveryId`, { rules: [{ required: true, message: '运费模版不能为空' }], initialValue: initRecord.deliveryId }]"
              placeholder="请选择运费模版"
            >
              <a-select-option v-for="value in goodsFreights" :key="value.id" :value="value.id">
                {{ value.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="商品状态" v-bind="formItemLayout">
            <a-select
              :showArrow="true"
              v-decorator="['status', { rules: [{ required: true, message: '请选择' }], initialValue: initRecord.goodsStatus }]"
              placeholder="请选择"
              :options="[
                  { key: 1, value: 1, title: '上架' },
                  { key: 2, value: 2, title: '下架' }
                ]"
            >
            </a-select>
          </a-form-item>
          <a-form-item label="是否推荐" v-bind="formItemLayout">
            <a-select
              :showArrow="true"
              v-decorator="['recommend', { initialValue: initRecord.recommend }]"
              placeholder="请选择"
              :options="[
                  { key: 0, value: 0, title: '是' },
                  { key: 1, value: 1, title: '否' }
                ]"
            >
            </a-select>
          </a-form-item>
          <a-form-item label="权重" v-bind="formItemLayout">
            <a-input-number
              style="width: 100%"
              :min="0"
              :precision="0"
              v-decorator="['weight', {  initialValue: initRecord.goodsSort }]"
            />
          </a-form-item>
        </a-form>
      </a-spin>
    </template>
  </modal>
</template>
<script>
import modal from '~/tool/modal';
import RichEditor from '@/components/editor/RichEditor';
import dictURL from 'utils/dictType';
import {fileOperationWithRenderImageData} from '@/mixin/image-operation';
import {regexp} from 'utils/common';

const formItemLayout = {
  labelCol: {span: 4},
  wrapperCol: {span: 19}
};

const renderImageData = [
  {
    inputTitle: '商品图片',
    dataIndex: 'image',
    required: true,
    accept: '.png, .jpg, .jpeg',
    extra: '（仅支持上传.png, .jpg, .jpeg格式，图片大小：750*750）',
    fileList: []
  }
];

export default {
  name: 'add',
  components: {
    modal,
    RichEditor
  },
  mixins: [fileOperationWithRenderImageData],
  props: {
    // 新增：0，编辑：1
    addOrEdit: {
      type: Number,
      default: 0
    },
    initRecord: {
      type: Object,
      default: () => ({})
    },
    visible: {
      default: false
    },
    // 新增记录
    apiURL: {
      type: Object,
      default: () => ({})
    },
    // 商品类别
    goodsCategorys: {
      type: Array,
      value: []
    },
    // 运费模版
    goodsFreights: {
      type: Array,
      value: []
    }
  },

  data() {
    return {
      regexp,
      renderImageData: JSON.parse(JSON.stringify(renderImageData)),
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      // 需要提交的数据
      submitData: {},
      // tags: [],
      // pickedTags: [],
      content: '',
      intro: '',
      isShowAddSpecificationBtn: true,
      specList: [],  // 界面上显示的spec
      dictURL,
      typeList: [],  // 二级分类
      specItems: [], // 有效的spec
      specSKUColumns: [],
      specSKUItems: [],  // sku数组
      specObj: {}, // 结果对象
      specArr: [], // 结果数组
      specNum: 0, // 判断是在第几层，用作keys的index
      specKeys: [],
    };
  },
  methods: {
    handleSelect(name) {
      const ext = this.labels.indexOf(name) > -1
      if (ext) return
      this.addLabel(name)
    },
    handleEditorChange(html) {
      this.content = html
    },
    introChange(html) {
      this.intro = html
    },
    // ---------------------- 界面交互事件 -------------------------
    //更加分类类别查询二级分类
    categoryChange(value){
      let paramsTemp = {};

      if (value){
        let temp = this.goodsCategorys.filter(item=>item.id===value);
        this.$set(this.initRecord,'dictType',undefined)
        this.$set(paramsTemp,'dictType',temp[0].name)
      }else {
        let temp = this.goodsCategorys.filter(item=>item.id===this.initRecord.categoryId);
        this.$set(paramsTemp,'dictType',temp[0].name)
      }
      console.log(paramsTemp)
      this.$get(dictURL.getRecords, paramsTemp).then(r => {
        this.typeList = r.data.data.rows;

      })
    },


    // 规格-添加规格
    addSpecificationBtnClick() {
      let that = this;
      if (that.loading) {
        return;
      }
      that.isShowAddSpecificationBtn = false;
      this.form.setFieldsValue({
        specificationNameInput: '',
        specificationValueInput: ''
      });
    },
    // 规格-保存
    saveSpecificationBtnClick() {
      let that = this;
      if (that.loading) {
        return;
      }
      that.form.validateFields(['specificationNameInput', 'specificationValueInput'], (err, values) => {
        if (!err) {
          let tmpObj = that.form.getFieldsValue();
          that.loading = true;
          that.$post(that.apiURL.addSpec, {
            specName: tmpObj.specificationNameInput
          }).then(r => {
            var specItem = {
              ...r.data.data,
              values: [],
              specValueInput: ''
            };
            that.$post(that.apiURL.addSpecValue, {
              specId: r.data.data.id,
              specValue: tmpObj.specificationValueInput
            }).then(r => {
              let specValueItem = r.data.data;
              specItem.values.push(specValueItem);
              that.specList.push(specItem);
              that.isShowAddSpecificationBtn = true;
              that.loading = false;
              this.getSKUList(that.specList);
            }).catch(r => {
              that.loading = false;
            });
          });
        }
      });
    },
    // 规格-取消
    cancelSpecificationBtnClick() {
      let that = this;
      if (that.loading) {
        return;
      }
      that.isShowAddSpecificationBtn = true;
    },
    // 规格-保存规格值
    saveSpecificationValueBtnClick(specIndex) {
      let that = this;
      if (that.loading) {
        return;
      }
      let specItem = that.specList[specIndex];
      let specValue = specItem.specValueInput;
      if (specValue.length == 0) {
        return;
      }
      that.loading = true;
      that.$post(that.apiURL.addSpecValue, {
        specId: specItem.id,
        specValue: specValue
      }).then(r => {
        let specValueItem = r.data.data;
        specItem.values.push(specValueItem);
        specItem.specValueInput = '';
        that.specList[specIndex] = specItem;
        that.loading = false;
        this.getSKUList(that.specList);
      }).catch(r => {
        that.loading = false;
      });
    },
    // 规格-删除规格
    deleteSpecificationBtnClick(specIndex) {
      let that = this;
      if (that.loading) {
        return;
      }
      this.$confirm({
        title: '确定要删除当前规格吗？',
        content: '',
        okText: '确定',
        cancelText: '取消',
        onOk() {
          that.specList.splice(specIndex, 1);
          that.getSKUList(that.specList);
        }
      });
    },
    // 规格-删除规格值
    deleteSpecificationValueBtnClick(specIndex, specValueIndex) {
      let that = this;
      if (that.loading) {
        return;
      }
      this.$confirm({
        title: '确定要删除当前规格属性值吗？',
        content: '',
        okText: '确定',
        cancelText: '取消',
        onOk() {
          let item = that.specList[specIndex];
          item.values.splice(specValueIndex, 1);
          that.specList[specIndex] = item;
          that.getSKUList(that.specList);
        }
      });
    },
    // 规格-生成sku
    getSKUList(specList, goodsSpecList1 = []) {
      let that = this;
      var newSpecList = [];
      var params1 = [];
      var params2 = [];
      for (var i = 0; i < specList.length; i++) {
        let itemm = specList[i];
        let subSpecList = itemm.values;
        var spec1 = [];
        var spec2 = [];
        for (var j = 0; j < subSpecList.length; j++) {
          spec1.push(subSpecList[j].specValue);
          spec2.push({
            id: subSpecList[j].id,
            name: subSpecList[j].specValue
          })
        }
        if (subSpecList.length > 0) {
          newSpecList.push(itemm);
          params1.push({
            name: itemm.specName,
            spec: spec1
          });
          params2.push({
            id: itemm.id,
            name: itemm.specName,
            spec: spec2
          });
        }
      }
      that.specItems = newSpecList;
      that.specKeys = [];
      params1.forEach(item => {
        that.specKeys.push(item.name);
      });
      let arr1;
      // 判断是否只有一组规格
      if (params1.length == 0) {
        that.specSKUColumns = [];
        that.specSKUItems = [];
        return;
      } else if (params1.length == 1) {
        arr1 = params1[0].spec;
      } else {
        for (let j = params1.length - 1, i = j; i >= 0; i--) {
          if (!arr1) {
            params1[i - 1].spec.push(params1[i].spec);
            arr1 = params1[i - 1].spec;
            if (i <= 1) break;
            i = i - 2;
          }
          params1[i].spec.push(arr1);
          arr1 = params1[i].spec;
        }
      }
      that.specObj = {}; // 结果对象
      that.specArr = []; // 结果数组
      that.specNum = 0;  // 判断是在第几层，用作keys的index
      // 调用deepClone函数将处理好的数组传入
      that.deepClone(arr1);
      var specSKUItems = [];
      for (var i = 0; i < that.specArr.length; i++) {
        let specArrItem = that.specArr[i];
        var m = 0;
        var goodsNo = "";
        var goodsPrice = "";
        var linePrice = "";
        var stockNum = "";
        var goodsWeight = "";
        var specSkuId = "";
        var specImage = "";
        for (const specItemKey in specArrItem) {
          for (var j = 0; j < params2.length; j++) {
            let paramsItem = params2[j];
            if (specItemKey == paramsItem.name) {
              let subItems = paramsItem.spec;
              for (var k = 0; k < subItems.length; k++) {
                let subItem = subItems[k];
                if (specArrItem[specItemKey] == subItem.name) {
                  specSkuId = specSkuId + (m == 0 ? '' : '_') + subItem.id;
                  m++;
                  break;
                }
              }
              break;
            }
          }
        }
        let specItem = {
          ...specArrItem,
          goodsNo,
          goodsPrice,
          linePrice,
          stockNum,
          goodsWeight,
          specSkuId,
          specImage,
          id: i + 1
        };
        specSKUItems.push(specItem);
      }
      // 处理特殊情况：多规格编辑的时候
      if (goodsSpecList1.length > 0) {
        for (var i = 0; i < goodsSpecList1.length; i++) {
          var goodsSpecItem1 = goodsSpecList1[i];
          for (var j = 0; j < specSKUItems.length; j++) {
            var specSKUItem1 = specSKUItems[j];
            if (goodsSpecItem1.specSkuId == specSKUItem1.specSkuId) {
              specSKUItems[j].goodsNo = goodsSpecItem1.goodsNo;
              specSKUItems[j].goodsPrice = goodsSpecItem1.goodsPrice;
              specSKUItems[j].goodsWeight = goodsSpecItem1.goodsWeight;
              specSKUItems[j].linePrice = goodsSpecItem1.linePrice;
              specSKUItems[j].specImage = goodsSpecItem1.specImage;
              specSKUItems[j].stockNum = goodsSpecItem1.stockNum;
              break;
            }
          }
        }
      }
      var specSKUColumns = [{
        title: '序号',
        dataIndex: 'id',
        key: 0,
        align: 'center'
      }];
      for (var i = 0; i < newSpecList.length; i++) {
        let specListItem = newSpecList[i];
        let specSKUColumnItem = {
          title: specListItem.specName,
          dataIndex: specListItem.specName,
          key: i + 1,
          align: 'center'
        };
        specSKUColumns.push(specSKUColumnItem);
      }
      specSKUColumns.push({
        title: '商品编码',
        dataIndex: 'goodsNo',
        key: specSKUColumns.length,
        align: 'center',
        scopedSlots: {customRender: "goodsNoScoped"}
      });
      specSKUColumns.push({
        title: '销售价',
        dataIndex: 'goodsPrice',
        key: specSKUColumns.length,
        align: 'center',
        scopedSlots: {customRender: "goodsPriceScoped"}
      });
      specSKUColumns.push({
        title: '划线价',
        dataIndex: 'linePrice',
        key: specSKUColumns.length,
        align: 'center',
        scopedSlots: {customRender: "linePriceScoped"}
      });
      specSKUColumns.push({
        title: '库存',
        dataIndex: 'stockNum',
        key: specSKUColumns.length,
        align: 'center',
        scopedSlots: {customRender: "stockNumScoped"}
      });
      specSKUColumns.push({
        title: '重量(kg)',
        dataIndex: 'goodsWeight',
        key: specSKUColumns.length,
        align: 'center',
        scopedSlots: {customRender: "goodsWeightScoped"}
      });
      specSKUColumns.push({
        title: '封面',
        dataIndex: 'specImage',
        key: specSKUColumns.length,
        align: 'center',
        scopedSlots: {customRender: "specImageScoped"}
      });
      specSKUColumns.push({
        title: '操作',
        dataIndex: 'uploadImage',
        key: specSKUColumns.length,
        align: 'center',
        scopedSlots: {customRender: "uploadImageScoped"}
      });
      that.specSKUColumns = specSKUColumns;
      that.specSKUItems = specSKUItems;
    },
    // 规格-deepClone函数内的逻辑处理
    deepClone(data) {
      let that = this;
      for (let i = 0; i < data.length; i++) {
        if (data[i] instanceof Array) {
          that.specNum--;
          return;
        }
        that.specObj[that.specKeys[that.specNum]] = data[i];
        if (data[data.length - 1] instanceof Array) {
          that.specNum++;
          that.deepClone(data[data.length - 1]);
        } else {
          let obj1 = JSON.parse(JSON.stringify(that.specObj));
          that.specArr.push(obj1);
        }
        if (i === data.length - 1) {
          that.specNum--;
        }
      }
    },
    // 规格-阻止系统的上传封面行为
    beforeCoverImageUpload() {
      return false;
    },
    // 规格-封面
    handleCoverImageChange(record, info) {
      let that = this;
      if (that.loading) {
        return;
      }
      // let fileList = info.fileList;
      let file = info.file;
      if (file.status === "removed") {
        // this.removeImageInFE(name, index, file);
        return;
      } else {
        if (file.size > 5 * 1024 * 1024) {
          // 文件不大于5MB
          this.loading = false;
          this.$message.error("文件过大，上传失败");
          return;
        }
        this.loading = true;
        const formData = new FormData();
        var timestamp = new Date().getTime();
        const oldFileName = file.name;
        const newFileName = oldFileName.replace(".", timestamp + ".");
        const newFile = new File([file], newFileName)
        formData.append("file", newFile);
        formData.append('forceUpdate', '1');
        formData.append('path', 'm1/' + newFileName);
        this.$upload(this.apiURL.uploadCommonImg, formData)
          .then(r => {
            let data = r.data.data;
            if (r.data.code === 200) {
              record.specImage = data.absPath;
              this.loading = false;
            }
          })
          .catch(r => {
            console.error(r);
            // this.removeImageInFE(name, index, file);
            this.loading = false;
          });
      }
    },
    // 重置
    reset() {
      this.loading = false
      this.content = ''
      this.intro = ''
      this.pickedTags = []
      this.form.resetFields()
    },
    // 关闭弹窗
    onClose() {
      this.$confirm({
        title: '确定放弃编辑吗？',
        content: '',
        okText: '确定',
        cancelText: '取消',
        onOk: this.onCloseConfirm
      });
    },
    // 确定关闭弹窗
    onCloseConfirm() {
      this.reset();
      this.$emit('close');
    },
    // 新增提交
    handleSubmit() {
      let that = this;
      let tmpObj = that.form.getFieldsValue();
      var validateFieldArr = [];
      if (tmpObj.stat == 1) {
        validateFieldArr = ['title', 'categoryId', 'image', 'stat', 'defalutSales', 'sales', 'weight', 'deliveryId', 'status','dictType','recommend', 'code', 'price', 'linePrice', 'currentCount', 'stats'];
      } else if (tmpObj.stat == 2) {
        validateFieldArr = ['title', 'categoryId', 'image', 'stat', 'defalutSales', 'sales', 'weight', 'deliveryId', 'status','dictType','recommend'];
      }
      that.form.validateFields(validateFieldArr, (err, values) => {
        if (!err) {
          // 规格判断
          if (tmpObj.stat == 2) {
            if (this.specItems.length == 0 || this.specSKUItems.length == 0) {
              that.$message.warning('请至少添加一个规格');
              return;
            }
            for (var i = 0; i < this.specSKUItems.length; i++) {
              let specSKUItem = this.specSKUItems[i];
              if (specSKUItem.goodsNo.length == 0 || specSKUItem.goodsPrice.length == 0 || specSKUItem.linePrice.length == 0 || specSKUItem.stockNum.length == 0 || specSKUItem.goodsWeight.length == 0 || specSKUItem.specImage.length == 0) {
                that.$message.warning('请完善规格明细表');
                return;
              }
            }
          }
          that.$confirm({
            title: '确定保存吗？',
            content: '',
            okText: '确定',
            cancelText: '取消',
            onOk: that.handleConfirmSubmit
          });
        }
      });
    },
    // 确定新增提交
    handleConfirmSubmit() {
      let that = this;
      this.loading = true;
      let tmpObj = this.form.getFieldsValue();
      var specImage = '';
      that.renderImageData.forEach(el => {
        if (!!el.fileList.length) {
          let tmpList = [];
          el.fileList.forEach(file => {
            specImage = file.url;
            tmpList.push(file.url);
          });
          let tmpStr = tmpList.join(',');
          tmpObj[el.dataIndex] = tmpStr;
        }
      });
      var data = {};
      if (tmpObj.stat == 1) {
        var goodsSpec = {
          goodsNo: tmpObj.code,
          goodsPrice: tmpObj.price,
          linePrice: tmpObj.linePrice,
          stockNum: tmpObj.currentCount,
          goodsWeight: tmpObj.currentWeight,
          specSkuId: '',
          specImage: specImage
        };
        data = {
          goodsName: tmpObj.title,
          categoryId: tmpObj.categoryId,
          dictType: tmpObj.dictType,
          images: tmpObj.image,
          specType: tmpObj.stat,
          deductStockType: tmpObj.stats,
          salesInitial: tmpObj.defalutSales,
          salesActual: tmpObj.sales,
          goodsSort: tmpObj.weight,
          deliveryId: tmpObj.deliveryId,
          content: that.content && that.content.length > 0 ? that.content : '',
          intro: that.intro && that.intro.length > 0 ? that.intro : '',
          goodsStatus: tmpObj.status,
          recommend: tmpObj.recommend,
          goodsSpec: goodsSpec
        };
      } else if (tmpObj.stat == 2) {
        var specList = [];
        var goodsSpecList = [];
        for (var i = 0; i < this.specItems.length; i++) {
          let specItem = this.specItems[i];
          let subSpecItems = specItem.values;
          for (var j = 0; j < subSpecItems.length; j++) {
            let subSpecItem = subSpecItems[j];
            specList.push({
              specId: subSpecItem.specId,
              specValueId: subSpecItem.id
            });
          }
        }
        for (var i = 0; i < this.specSKUItems.length; i++) {
          let specSKUItem = this.specSKUItems[i];
          goodsSpecList.push({
            goodsNo: specSKUItem.goodsNo,
            goodsPrice: specSKUItem.goodsPrice,
            linePrice: specSKUItem.linePrice,
            stockNum: specSKUItem.stockNum,
            goodsWeight: specSKUItem.goodsWeight,
            specSkuId: specSKUItem.specSkuId,
            specImage: specSKUItem.specImage
          });
        }
        data = {
          goodsName: tmpObj.title,
          categoryId: tmpObj.categoryId,
          dictType: tmpObj.dictType,
          images: tmpObj.image,
          specType: tmpObj.stat,
          deductStockType: tmpObj.stats,
          salesInitial: tmpObj.defalutSales,
          salesActual: tmpObj.sales,
          goodsSort: tmpObj.weight,
          deliveryId: tmpObj.deliveryId,
          content: that.content && that.content.length > 0 ? that.content : '',
          intro: that.intro && that.intro.length > 0 ? that.intro : '',
          goodsStatus: tmpObj.status,
          goodsSpecList: goodsSpecList,
          recommend: tmpObj.recommend,
          specList: specList
        };
      }
      if (that.addOrEdit != 0) {
        data.id = that.initRecord.id;
      }
      this.$post(that.addOrEdit == 0 ? this.apiURL.addRecords : this.apiURL.editRecords, data, 2).then(r => {
        this.reset();
        this.$emit('success');
      }).catch(() => {
        this.loading = false;
      });
    },
  },
  mounted() {
    this.categoryChange();
    if (this.addOrEdit && this.visible) {
      this.renderImageList();
      if (this.initRecord.specType == 2) {
        // 编辑时，多规格数据处理
        var specList = this.initRecord.specList;
        var goodsSpecList = this.initRecord.goodsSpecList;
        this.getSKUList(specList, goodsSpecList);
        // var goodsSpecList = this.initRecord.goodsSpecList;
        // var newSpecList = [];
        // var newSpecId = '';
        // var newSpecItem = {};
        // for (var i = 0; i < specList.length; i++) {
        //   var specItem = specList[i];
        //   if (newSpecId != specItem.specId) {
        //     newSpecList.push(newSpecItem);
        //     newSpecId = specItem.specId;
        //     newSpecItem = {
        //       createTime: '',
        //       id: specItem.specId,
        //       specName: specItem.specName,
        //       specValueInput: '',
        //       userId: '',
        //       values: [
        //         {
        //           createTime: '',
        //           specId: specItem.specId,
        //           id: specItem.specValueId,
        //           specValue: specItem.specValue,
        //           userId: ''
        //         }
        //       ]
        //     };
        //   } else {
        //     newSpecItem.values.push({
        //       createTime: '',
        //       specId: specItem.specId,
        //       id: specItem.specValueId,
        //       specValue: specItem.specValue,
        //       userId: ''
        //     });
        //   }
        // }
      }
    }
    if (this.visible) {
      // 给form赋初值
      this.$nextTick(() => {
        setTimeout(() => {
          if (!this.addOrEdit) {
            this.form.setFieldsValue({
              stat: 1,
              stats: 1,
              status: 1,
              deliveryId: this.initRecord.deliveryId,
              specificationNameInput: '',
              specificationValueInput: ''
            });
          } else {
            this.content = this.initRecord.content;
            this.intro = this.initRecord.intro;
            // this.form.setFieldsValue({
            //   // stat: 1,
            //   specificationNameInput: '',
            //   specificationValueInput: ''
            // });
          }
        })
      });
    }
  },
  // watch: {
  //   visible(val) {
  //     if (val) {
  //       console.log('1111111111111111111111');
  //       console.log(this.initialValue);
  //       // 给form赋初值
  //       this.$nextTick(() => {
  //         setTimeout(() => {
  //           this.form.setFieldsValue({
  //             stat: 1,
  //             specificationNameInput: '',
  //             specificationValueInput: ''
  //           });
  //         })
  //       });
  //     }
  //   }
  // }
};
</script>
